package com.wlz.heartbeat;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author wlz
 * @date 2022-07-09  4:24 下午
 */
@Slf4j
public class MyHeartBeatNettyServerHandler extends SimpleChannelInboundHandler<String> {

    int readIdleTimes = 0;

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {

        log.info(" 接收到客户端发送的消息: {}", s);
        if ("Heartbeat Packet".equals(s)) {
            ctx.channel().writeAndFlush("ok");
        }else {
            log.info("  其他信息处理 .......");
        }
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        IdleStateEvent event = (IdleStateEvent) evt;
        String eventType = null;
        switch (event.state()) {
            case READER_IDLE:
                eventType = "读空闲";
                readIdleTimes++; // 读空闲的计数加1
                break;
            case WRITER_IDLE:
                eventType = "写空闲";
                break;
            case ALL_IDLE:
                eventType = "读写空闲";
                break;
        }

        log.info(" {}  超时事件: {} ", ctx.channel().remoteAddress(), eventType);
        if (readIdleTimes > 3) {
            log.info("【服务端】 读空闲超过3次，关闭连接，释放更多资源 。。。。");
            ctx.channel().writeAndFlush("idle close ...");
            ctx.channel().close();
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("=== {}  is active ", ctx.channel().remoteAddress());
    }
}
